package martin.tpfinal.grabar.grafico;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D.Double;

import javax.swing.*;
import javax.swing.border.*;

import java.util.Vector;
import java.io.*;

import javax.sound.sampled.*;

public class VentanaPrincipal extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;

	private final int bufSize = 16384;

	private FormatControls formatControls = new FormatControls();
	    
	private Reproducir playback = new Reproducir(this);

	private AudioInputStream audioInputStream;
	private SamplingGraph samplingGraph;

	private JButton captB, pausB;


	private String fileName = "untitled.wav";
	private String errStr;
	private double duration, seconds;
	private File file;
	private Vector<Double> lines = new Vector<Double>();

	private Capturar capture= new Capturar(this);

	private static JTextArea textAreaInfo;
	
	public VentanaPrincipal() {
		
		inicialice();
	
	}
	
	private void inicialice(){
	        
	    setLayout(new BorderLayout());
	    EmptyBorder eb = new EmptyBorder(5,5,5,5);
	    SoftBevelBorder sbb = new SoftBevelBorder(SoftBevelBorder.LOWERED);
	    setBorder(new EmptyBorder(5,5,5,5));

	    JPanel panelInterno = new JPanel();
	    panelInterno.setBorder(sbb);
	    panelInterno.setLayout(new BoxLayout(panelInterno, BoxLayout.Y_AXIS));

	        
	    JPanel buttonsPanel = new JPanel();
	    buttonsPanel.setBorder(new EmptyBorder(10,0,5,0));
	    captB = addButton("Grabar", buttonsPanel, true);
	    pausB = addButton("Pausar", buttonsPanel, false);
	        
	    panelInterno.add(buttonsPanel);


        JPanel samplingPanel = new JPanel(new BorderLayout());
        eb = new EmptyBorder(10,20,20,20);
        samplingPanel.setBorder(new CompoundBorder(eb, sbb));
        samplingPanel.add(samplingGraph = new SamplingGraph(this));
        panelInterno.add(samplingPanel);

	    JPanel msnPanel = new JPanel(new BorderLayout());
	    eb = new EmptyBorder(10,20,20,20);
	    msnPanel.setBorder(new CompoundBorder(eb, sbb));
	    textAreaInfo = new JTextArea(5, 20);
	    JScrollPane scrollPane = new JScrollPane(textAreaInfo); 
	    textAreaInfo.setEditable(false);
	    msnPanel.add(scrollPane);
	        
	    panelInterno.add(msnPanel);

	        
	    add(panelInterno);
	            
	}


	
    public void close() {
    	if (capture.getThread() != null) {
    		captB.doClick(0);
    	}
    }


    private JButton addButton(String name, JPanel p, boolean state) {
    	JButton b = new JButton(name);
    	b.addActionListener(this);
    	b.setEnabled(state);
    	p.add(b);
    	return b;
    }


    public void actionPerformed(ActionEvent e) {
    	Object obj = e.getSource();
    	if (obj.equals(captB)) {
    		if (captB.getText().startsWith("Grabar")) { //empieza a grabar
    			file = null;
    			capture.start();
    			fileName = "untitled";
    			samplingGraph.start();
    			pausB.setEnabled(true);
    			captB.setText("Parar");
    		} else {  //para de grabar
    			lines.removeAllElements();  
    			capture.stop();
    			samplingGraph.stop();
    			pausB.setEnabled(false);
    			captB.setText("Grabar");
    		}
    	} else if (obj.equals(pausB)) {  //pausa lo que este haciendo
    		if (pausB.getText().startsWith("Pausar")) {
    			if (capture.getThread() != null) {
    				capture.getLine().stop();
    			} else {
    				if (playback.getThread() != null) {
    					playback.getLine().stop();
    				}
    			}
    			pausB.setText("Continuar");
    		} else {   //continua con lo que estaba haciendo
    			if (capture.getThread() != null) {
    				capture.getLine().start();
    			} else {
    				if (playback.getThread() != null) {
    					playback.getLine().start();
    				}
    			}
    			pausB.setText("Pausar");
    		}
    	} 
    }


    public void createAudioInputStream(File file, boolean updateComponents) {
    	if (file != null && file.isFile()) {
    		try {
    			this.file = file;
    			errStr = null;
    			audioInputStream = AudioSystem.getAudioInputStream(file);
    			fileName = file.getName();
    			long milliseconds = (long)((audioInputStream.getFrameLength() * 1000) / audioInputStream.getFormat().getFrameRate());
    			duration = milliseconds / 1000.0;
    			if (updateComponents) {
    				samplingGraph.createWaveForm(null);
    			}
    		} catch (Exception ex) { 
    			reportStatus(ex.toString());
    		}
    	} else {
    		reportStatus("Audio file required.");
    	}	
    }


    public void saveToFile(String name, AudioFileFormat.Type fileType) {

    	if (audioInputStream == null) {
    		reportStatus("No loaded audio to save");
    		return;
    	} else if (file != null) {
    		createAudioInputStream(file, false);
    	}

    	// reset to the beginnning of the captured data
    	try {
    		audioInputStream.reset();
    	} catch (Exception e) { 
    		reportStatus("Unable to reset stream " + e);
    		return;
    	}

    	File file = new File(fileName = name);
    	try {
    		if (AudioSystem.write(audioInputStream, fileType, file) == -1) {
    			throw new IOException("Problems writing to file");
    		}
    		else {
				System.out.println("hola");
			}
    	} catch (Exception ex) { reportStatus(ex.toString()); }
    		samplingGraph.repaint();
    }
	        

    public void reportStatus(String msg) {
    	if ((errStr = msg) != null) {
    		System.out.println(errStr);
    		samplingGraph.repaint();
    	}
    }


    public String getErrStr() {
		return errStr;
	}

	public void setErrStr(String errStr) {
		this.errStr = errStr;
	}

	public SamplingGraph getSamplingGraph() {
		return samplingGraph;
	}

	public void setSamplingGraph(SamplingGraph samplingGraph) {
		this.samplingGraph = samplingGraph;
	}

	public JButton getCaptB() {
		return captB;
	}

	public void setCaptB(JButton captB) {
		this.captB = captB;
	}

	public JButton getPausB() {
		return pausB;
	}

	public void setPausB(JButton pausB) {
		this.pausB = pausB;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public AudioInputStream getAudioInputStream() {
		return audioInputStream;
	}

	public void setAudioInputStream(AudioInputStream audioInputStream) {
		this.audioInputStream = audioInputStream;
	}

	public FormatControls getFormatControls() {
		return formatControls;
	}

	public void setFormatControls(FormatControls formatControls) {
		this.formatControls = formatControls;
	}

	public int getBufSize() {
		return bufSize;
	}

    public Vector<Double> getLines() {
		return lines;
	}

	public void setLines(Vector<Double> lines) {
		this.lines = lines;
	}

	public double getDuration() {
		return duration;
	}

	public void setDuration(double duration) {
		this.duration = duration;
	}

	public double getSeconds() {
		return seconds;
	}

	public void setSeconds(double seconds) {
		this.seconds = seconds;
	}

	public Capturar getCapture() {
		return capture;
	}

	public void setCapture(Capturar capture) {
		this.capture = capture;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public Reproducir getPlayback() {
		return playback;
	}

	public void setPlayback(Reproducir playback) {
		this.playback = playback;
	}

	
	public static void updateTextAreaInfo(String mensaje){
	    textAreaInfo.setText(mensaje);
	}
	
	    
}
